namespace SimpleWebServices.Web
{
    using System;
    using System.Web;

    public static class Http
    {
        public static string ToCurrentProtocol(string value)
        {
            string result = null;

            if (string.IsNullOrEmpty(value) || null == HttpContextFactory.Current)
            {
                result = value;
            }
            else
            {
                try
                {
                    if (HttpContextFactory.Current.Request.IsSecureConnection)
                    {
                        result = value.StartsWith("http://", StringComparison.OrdinalIgnoreCase)
                            ? "https://" + value.Substring("http://".Length)
                            : value;
                    }
                    else
                    {
                        result = value.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
                            ? "http://" + value.Substring("https://".Length)
                            : value;
                    }
                }
                catch (HttpException)
                {
                    result = value;
                }
            }

            return result;
        }
    }
}